package com.ww.dynamic.spel;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class CollectionSample {

    public static void main(String[] args) {
        // 构建一个对象
        PropertyExprSample.User user = new PropertyExprSample.User();
        user.setUserName("tom");
        user.setLastVisit(new Date());
        user.setCredits(100);
        user.setPlaceOfBirth(new PropertyExprSample.PlaceOfBirth("中国", "厦门"));

        SpelExpressionParser parser = new SpelExpressionParser();
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setVariable("user", user);

        // 数组表达式解析
        int[] array1 = (int[]) parser.parseExpression("new int[]{1,2,3}").getValue(context);
        int[][] arrays = (int[][]) parser.parseExpression("new int[2][3]").getValue(context);

        // 目前不支持多维数组初始化

        // List表达式解析
        List list = (List) parser.parseExpression("{1,2,3,4}").getValue(context);
        List listOfLists = (List) parser.parseExpression("{{'a','b'},{'x','y'}}").getValue(context);

        // 列表字符串解析
        Map userInfo = (Map) parser.parseExpression("{userName:'tom',credits:100}").getValue(context);
        List userInfo2 = (List) parser.parseExpression("{{userName:'tom',credits:100},{userName:'tom',credits:100}}").getValue(context);

        // 从数组、List、Map中取值
        context.setVariable("interestsArray", array1);
        context.setVariable("interestsList", list);
        context.setVariable("interestsMap", userInfo);
        Integer interest1 = (Integer) parser.parseExpression("#interestsArray[0]").getValue(context);
        System.out.println(interest1);
        Integer interest2 = (Integer) parser.parseExpression("#interestsList[0]").getValue(context);
        System.out.println(interest2);
        String interest3 = (String) parser.parseExpression("#interestsMap['userName']").getValue(context);
        System.out.println(interest3);
    }

    @ToString
    @Data
    static class User {

        private String userName;

        private Date lastVisit;

        private Integer credits;

        private PropertyExprSample.PlaceOfBirth placeOfBirth;
    }

    @ToString
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    static class PlaceOfBirth {

        private String province;

        private String city;
    }
}
